var dedupe = require('dedupe')
var arrayUnique = require('./arrayUnique')

function test1() {
	var a = [1, 2, 2, 3]
	var b = dedupe(a)
	console.log(b)
	console.log(arrayUniqueV2(a))
	console.log(arrayUnique(a))
	//result: [1, 2, 3]



	console.log('-----------------------\n')

	var aa = [{a: 2}, {a: 1}, {a: 1}, {a: 1}]
	var bb = dedupe(aa)
	console.log(bb)
	console.log(arrayUnique(aa))
	console.log(arrayUniqueV2(aa))
}



function test2() {
	var aaa = [{a: 2, b: 1}, {a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 4}]
	var bbb = dedupe(aaa, value => value.a)
	console.log(bbb)
	console.log(arrayDedupe(aaa, value => value.a))
	console.log('-----------------------\n')
	var bbb = dedupe(aaa, value => value.b)
	console.log(bbb)
	console.log(arrayDedupe(aaa, value => value.b))
}

test2()


/**
 * 利用hasOwnProperty 判断是否存在对象属性, 所有的都去重了
 * @param  {[type]} array [description]
 * @return {[type]}       [description]
 */
function arrayUniqueV2 (array) {
	if (!Array.isArray(array)) {
       throw new TypeError('type error!')
    }
	
	var obj = {}
	var ret = array.filter(item => {
		// 根据类型和值 一起组合当做key
		var key = typeof item + JSON.stringify(item) + item;
		return obj.hasOwnProperty(key) ? false : (obj[key] = true)
	})

	return  ret 
}




function arrayDedupe(arr, hasher) {
	if(!hasher) {
		hasher = function(item) {
			return `${typeof item}_${JSON.stringify(item)}_${item}`
		}
	}

	var one, result = []
	for (var i = 0; i < arr.length; i++) {
		one = arr[i]
		for(var j = 0; j < result.length; j++) {
			if(hasher(one) === hasher(result[j])) {
				break
			}
		}

		// 没有重复值
		if(j === result.length) {
			result.push(one)
		}
	}
	return result 
}
